#include "xmsg_client.h"
#include <event2/bufferevent.h>
#include <event2/event.h>
#include "xmsg_com.pb.h"
#include <thread>
#include <iostream>
using namespace std;
static void ReadCB(struct bufferevent *bev, void *ctx)
{
    cout << "#" << flush;
    char buf[1024] = { 0 };
    int len = bufferevent_read(bev, buf, sizeof(buf) - 1);
    cout << buf << endl;
    //??buffer??
    bufferevent_write(bev, "OK", 3);
    //??????????????????????????
    this_thread::sleep_for(1000ms);
}

static void EventCB(struct bufferevent *bev, short what, void *ctx)
{
    cout << "client event" << endl;
    //???
    if (what & BEV_EVENT_TIMEOUT || what & BEV_EVENT_ERROR || what & BEV_EVENT_EOF)
    {
        cout << " BEV_EVENT_TIMEOUT BEV_EVENT_EOF" << endl;
        //???????

        //?????????
        bufferevent_free(bev);
        return;
    }

    if (what & BEV_EVENT_CONNECTED)
    {
        cout << "BEV_EVENT_CONNECTED" << endl;
        //bufferevent_write(bev, "OK", 3);
        xmsg::XLoginReq  req;
    }
}

//?????????????????????
void XMsgClient::Start()
{
    thread th(&XMsgClient::Main, this);
    th.detach();
}

//?????
void XMsgClient::Main()
{
    if (server_port_ <= 0)
    {
        cerr << "client error:please set the server port" << endl;
        return;
    }
    //??????
    this_thread::sleep_for(200ms);

    cout << "XMsgClient::Main begin!" << endl;
    event_base *base = event_base_new();
    //?????
    bufferevent *bev = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE);

    sockaddr_in sin;
    memset(&sin, 0, sizeof(sin));
    sin.sin_family = AF_INET;
    sin.sin_port = htons(this->server_port_);
    if (server_ip_.empty())
    {
        server_ip_ = "127.0.0.1";
    }
    evutil_inet_pton(AF_INET, this->server_ip_.c_str(), &sin.sin_addr.s_addr);

    //??????
    //?????? ????????
    bufferevent_enable(bev, EV_READ | EV_WRITE);

    //???? ?????1/1000000??  ??? ????
    timeval t1 = { 30,0 };
    bufferevent_set_timeouts(bev, &t1, 0);

    //??????
    bufferevent_setcb(bev, ReadCB, 0, EventCB, base);

    int re = bufferevent_socket_connect(bev, (sockaddr*)&sin, sizeof(sin));
    if (re != 0)
    {
        cerr << "bufferevent_socket_connect error" << endl;
        return;
    }

    /// ????? ????????? ?????????
    /// ???????????
    event_base_dispatch(base);
    event_base_free(base);

    cout << "XMsgClient::Main end!" << endl;
}



